package com.net.tkc.pro.controller;

import com.net.tkc.pro.entity.History;
import com.net.tkc.pro.entity.Opt;
import com.net.tkc.pro.entity.ResultEntity;
import com.net.tkc.pro.impl.HistoryImpl;
import com.net.tkc.pro.impl.OptImpl;
import com.net.tkc.pro.tool.JsonUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin //解决跨域问题
@RestController
@RequestMapping("/Opt/")
public class OptController {
    ResultEntity resultEntity = null;
    @Resource
    OptImpl optImpl;

    /**
     * 通过用户id查询历史成绩
     * @param userid
     * @return
     */
    @GetMapping("Opt")
    private String getOptList(
            @RequestParam("userid") int userid
    ){
        resultEntity = new ResultEntity();
        try{
            List<Opt> list =optImpl.getOptList(userid);
            if (list.size()!=0){
                resultEntity.setCount(list.size());
                resultEntity.setCode("0");
                resultEntity.setData(list);
                resultEntity.setMsg("获取成功！");
            }else{
                resultEntity.setMsg("获取失败,请查看是否有数据");
                resultEntity.setCode("2");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setMsg("获取失败");
            resultEntity.setCode("1");
        }
        return JsonUtil.getJsonTool().toJson(resultEntity);
    }
    /**
     * 记录成绩
     * @param userid 用户id
     * @param categoryid 题库id
     * @param achievement 成绩
     * @return
     */
    @PostMapping("Opt")
    private String addOpt(
            @RequestParam("userid") int userid,
            @RequestParam("categoryid") int categoryid,
            @RequestParam("achievement") String achievement
    ){
        resultEntity = new ResultEntity();
        DateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date=new Date();
        String Time=dateFormat.format(date);
        Opt opt=new Opt();
        opt.setDtTime(Time);
        opt.setUserid(userid);
        opt.setCategoryid(categoryid);
        opt.setAchievement(achievement);
        try{
            int result = optImpl.addOpt(opt);
            if(result>0){
                resultEntity.setCode("0");
                resultEntity.setMsg("添加成功！");
            }else{
                resultEntity.setCode("1");
                resultEntity.setMsg("添加失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            resultEntity.setCode("9999");
            resultEntity.setMsg(e.getMessage());
        }
        return JsonUtil.getJsonTool().toJson(resultEntity);
    }
}
